package com.lin.missyou.core.hack;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * 自动通过文件夹指定 Controller 访问路径
 * RequestMappingHandlerMapping 专门用来处理 RequestMapping的
 * @author gcq
 * @Create 2021-10-05
 */
public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {

    /**
     * 获取配置文件定义的根路径
     */
    @Value("${missyou.api-package}")
    private String apiPackagePath;

    /**
     * 指定controller的访问前缀
     * @param method
     * @param handlerType
     * @return
     */
    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
        if(mappingInfo != null) {
            String prefix = this.getPrefix(handlerType);
            // 合并
            return RequestMappingInfo.paths(prefix).build().combine(mappingInfo);
        }
        return mappingInfo;
    }

    /**
     * 获取api根目录下的包名
     * @param handlerType
     * @return
     */
    private String getPrefix(Class<?> handlerType){
        String packageName = handlerType.getPackage().getName();
        String dotPath = packageName.replaceAll(this.apiPackagePath, "");
        return dotPath.replace(".", "/");
    }
}